// ActionScript file
import flash.events.Event;

import jpa.domain.Department;

import mx.collections.ArrayCollection;
import mx.controls.Alert;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import mx.rpc.remoting.mxml.RemoteObject;
			
			[Bindable]
			private var contacts:ArrayCollection;
			
			private var ro:RemoteObject;

			private function resultHandler(event:ResultEvent):void
			{
				contacts = event.result as ArrayCollection
			}

			private function faultHandler(event:FaultEvent):void
			{
				Alert.show(event.fault.faultDetail);
			}

			public function openContact(department:Department):void
			{
				var children:Array = tn.getChildren();
				for (var i:int = 0; i<children.length; i++)
				{
					if (DepartmentForm(children[i]).department.id == department.id)
					{
						tn.selectedChild = children[i];
						return;
					}
				}
				
				var form:DepartmentForm = new DepartmentForm();
				form.addEventListener(DepartmentEvent.CREATED, contactCreatedHandler);
				form.addEventListener(DepartmentEvent.UPDATED, contactUpdatedHandler);
				form.addEventListener(DepartmentEvent.DELETED, contactDeletedHandler);
				tn.addChild(form);
				form.department = department;
				tn.selectedChild = form;
			}
			
			public function getCarInfoById(evt:Event):void{
				var id:uint=contacts[evt.currentTarget.selectedIndex]['id'];
				ro=Global.getRemoteObject("departmentController",true,getCarInfoByIdHandler);
				ro.getDepartmentById(id);
			}
			
			
			private function getCarInfoByIdHandler(event:ResultEvent):void
			{
				var department:Department = event.result as Department;
				
				openContact(department);
			}

			private function search():void
			{
				
				ro=Global.getRemoteObject("departmentController",true,resultHandler);
				ro.getMyDepartmentList();
			}

			private function contactCreatedHandler(event:DepartmentEvent):void
			{
				search();				
			}

			private function contactUpdatedHandler(event:DepartmentEvent):void
			{
				search();				
			}

			private function contactDeletedHandler(event:DepartmentEvent):void
			{
				tn.removeChild(event.target as DepartmentForm);
				search();				
			}